<template>
    <el-form :model="loginForm" class="animate__animated animate__backInDown login-form">
        <el-form-item>
            <el-input v-model="loginForm.username" placeholder="请输入用户名" clearable autofocus autocomplete>
                <template #prefix>
                    <lemon-icon :size="20" icon="User" />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" clearable show-password>
                <template #prefix>
                    <lemon-icon :size="20" icon="Key" />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-input v-model="loginForm.code" placeholder="请输入验证码" clearable @keydown.enter="onLogin" class="input-code">
                <template #prefix>
                    <lemon-icon :size="20" icon="Cellphone" />
                </template>
                <template #append>
                    <el-image @click="onRefreshCode" class="code" :src="src" fit="fill" />
                    <div class="time">{{ timer }}s</div>
                </template>
            </el-input>
            <div class="form-btn-password">
                <span class="forget-password" @click="forgetPasswordDialog = true"> 忘记密码？</span>
            </div>
        </el-form-item>
        <el-form-item>
            <div class="form-btn">
                <el-button type="primary" round @click="onLogin"> 登录 </el-button>
                <el-button round @click="goRegister">去注册</el-button>
            </div>
        </el-form-item>
    </el-form>

    <!-- 忘记密码 -->
    <el-dialog v-model="forgetPasswordDialog" title="忘记密码" center :draggable="true" :append-to-body="true" width="500" @close="onCancel" class="animate__animated animate__fadeInDown">
        <forget-password @on-cancel="onCancel" />
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, inject, ref, onMounted, onBeforeUnmount } from "vue";
import { delay } from "@/utils/common";
import ForgetPassword from "@/views/index/ForgetPassword.vue";

//获取自定义全局方法
const { axios, http, authStore, baseURL, encrypt, emitter } = inject<any>("method");

const loginForm = reactive({
    username: "",
    password: "",
    code: "",
});

//登录
const onLogin = async () => {
    if (loginForm.username?.trim() == "") {
        emitter.emit("msg-error", "请输入用户名");
    } else if (loginForm.password?.trim() == "") {
        emitter.emit("msg-error", "请输入密码");
    } else if (loginForm.code?.trim() == "") {
        emitter.emit("msg-error", "请输入验证码");
    } else {
        emitter.emit("loading-open", { target: ".el-form", text: "登录中..." });
        const data = await axios.post(`${baseURL}/login`, { username: loginForm.username, password: encrypt(loginForm.password), code: loginForm.code }, { headers: { uuid: uuid.value } });
        emitter.emit("loading-close");
        if (data?.data?.success) {
            emitter.emit("msg-success", data?.data?.data);
            authStore.setAccessToken(data?.headers["authorization"]);
            authStore.setRefreshToken(data?.headers["x-refresh-token"]);
            //1.并行执行两个请求[加载路由,加载路由对应的资源信息]
            const [routers, routerResource] = await Promise.all([http.get("/getRouters"), http.get("/getRouterResource")]);
            authStore.setRoutes(routers);
            authStore.setRouterResourceList(routerResource);
            //2.获取请求路由中的所有路径
            const uris = routers.map((item: any) => `${item.parentUri}/${item.childUri}`);
            if (uris && uris.length > 0) {
                //3.执行页面跳转
                await delay(2000);
                emitter.emit("router-push", uris.includes("/system/home") ? "/system/home" : uris[0]);
            } else {
                emitter.emit("msg-error", "未授权操作，请联系系统管理员！");
            }
        } else {
            onRefreshCode();
            emitter.emit("msg-error", { message: data?.data?.message, duration: 3000 });
        }
    }
};

//使用defineEmits注册一个自定义事件
const emit = defineEmits(["switchPage"]);

//去注册
const goRegister = () => emit("switchPage", false);

//忘记密码弹窗
const forgetPasswordDialog = ref(false);

//验证码路径
const src = ref<string | undefined>();

//刷新验证码的uuid
const uuid = ref<string | undefined>();
const onRefreshCode = async () => {
    const data = await axios.get(`${baseURL}/getCaptcha?${new Date().getTime()}`);
    src.value = data?.data?.data;
    uuid.value = data?.headers?.uuid;
    timer.value = 60;
    clearInterval(intervalId.value);
    loginForm.code = "";
    initTime();
    emitter.emit("loading-close");
};

//时间
const timer = ref(60);
const intervalId = ref();
const initTime = () => {
    intervalId.value = setInterval(() => {
        if (timer.value >= 1) {
            timer.value = timer.value - 1;
        } else {
            clearInterval(intervalId.value);
        }
    }, 1000);
};

//关闭忘记密码弹窗
const onCancel = () => {
    forgetPasswordDialog.value = false;
    onRefreshCode();
};

onMounted(() => onRefreshCode());

//卸载前执行
onBeforeUnmount(() => {
    clearInterval(intervalId.value);
});
</script>

<style scoped lang="less">
.login-form :deep(.el-input__wrapper) {
    background-color: rgba(252, 251, 251, 0.7);
}
.form-label {
    color: white;
}

.form-btn-password {
    width: 100%;
    padding: 0 15px;

    .forget-password {
        float: right;
        font-size: 14px;
        color: white;
        cursor: pointer;
    }

    .forget-password:hover {
        color: var(--el-color-primary);
    }
}

.form-btn {
    text-align: center;
    width: 100%;

    .el-button {
        width: 25%;
    }
}

.input-code:deep(.el-input-group__append) {
    padding: 0 3px;
    background-color: rgba(252, 251, 251, 0.7);
    border: 1px solid rgb(145, 144, 144);
}

.code {
    width: 100%;
    height: 40px;
    border-right: 1px solid;
    background-color: rgba(252, 251, 251, 0);
    cursor: pointer;
}

.time {
    width: 70px;
    text-align: center;
    font-size: large;
    font-weight: bolder;
    color: rgb(160, 10, 10);
}
</style>
